import qs from 'qs';
import { ref, reactive, onMounted, nextTick } from "vue";
import { GetMenuBy } from "@/api/stu/bigdataprocessing"
import { type PaginationProps } from "@pureadmin/table";
import { GetLearningAssessment, UpdateLearningAssessment, DeleteLearningAssessment } from "@/api/admin/python"
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
export function useIndex() {
  const dataList = ref([]);
  const loading = ref(false);
  const VisibleTitle = ref("");
  const updatePanelVisible = ref(false);
  const isdisabled = ref<boolean>(false);
  // 获取题目列表
  const SubmitFrom = reactive({
    moduleId: {},
    menuId: "",
    questionType: "",
    title: ""
  });
  // 添加题目
  const updateFrom = reactive({
    learningAssessmentId: null, //0 为添加
    menuId: "",
    moduleId: "",
    MenuName: "",
    moduleName: "",
    questionType: "",
    title: "",
    answerA: "",
    answerB: "",
    answerC: "",
    answerD: "",
    answerE: "",
    trueAnswer: "",
    remark: ""
  })
  // from 搜索表
  const ListFrom = reactive<any>({
    ModelList: [],
    ChildList: [],
    QuestionType: [
      { id: "1", title: "单选题" },
      { id: "2", title: "多选题" },
      { id: "3", title: "判断题" }
    ]
  })

  const ListFroms = reactive<any>({
    ModelList: [],
    ChildList: [],
    QuestionType: [
      { id: "1", title: "单选题" },
      { id: "2", title: "多选题" },
      { id: "3", title: "判断题" }
    ]
  })
  // 列表头部
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "模块名称",
      prop: "moduleName",
      minWidth: 200
    }, {
      label: "菜单名称",
      prop: "menuName",
      minWidth: 200
    }, {
      label: "题型",
      prop: "questionType",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <span>
          {
            row.questionType === "1" ? "单选题" :
              row.questionType === "2" ? "多选题" : "判断题"
          }
        </span>
      )
    }, {
      label: "题目",
      prop: "title",
      minWidth: 220
    }, {
      label: "正确答案",
      prop: "trueAnswer",
      minWidth: 100
    }, {
      label: "创建时间",
      prop: "createTime",
      minWidth: 150
    }, {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ]
  // 分页
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 校验表单
  const rules = {
    moduleId: [{
      required: true,
      message: "请选择模块名称！",
      trigger: ["blur", "change"]
    }],
    menuId: [{
      required: true,
      message: "请选择菜单名称！",
      trigger: ["blur", "change"]
    }],
    questionType: [{
      required: true,
      message: "请选择题目类型！",
      trigger: ["blur", "change"]
    }],
    trueAnswer: [{
      required: true,
      message: "请输入正确答案！",
      trigger: ["blur", "change"]
    }]
  }

  /************************** 方法 *****************************/

  // 获取模块名称 -- 菜单列表
  async function getModulName() {
    const menuid = qs.stringify({ moudleId: 687 });
    const respone = await GetMenuBy(menuid);
    ListFrom.ModelList = respone.data;
    ListFroms.ModelList = respone.data;
  }

  // 获取子菜单
  function GetModulChildrens(row: any) {
    SubmitFrom.menuId = ""
    ListFrom.ChildList = row.childrens;
  }

  function GetModulChildrenss(row: any) {
    updateFrom.menuId = ""
    ListFroms.ChildList = row.childrens;
  }

  // 搜索
  async function SearchForm() {
    const SubData = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      moduleId: SubmitFrom.moduleId.id,
      menuId: SubmitFrom.menuId,
      // menuId: "c51bcceb0afc4d2197941801f43afa6b",
      questionType: SubmitFrom.questionType,
      title: SubmitFrom.title
    }
    loading.value = true;
    const respone = await GetLearningAssessment(SubData);
    const { data } = respone;
    if (respone.success) {
      dataList.value = data.list;
      loading.value = false;
      pagination.total = data.totalCount;

    }
  }

  // 删除
  async function handleDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      // 确定
      const learningAssessmentId = qs.stringify({ learningAssessmentId: row.learningAssessmentId })
      const respone = await DeleteLearningAssessment(learningAssessmentId);
      if (respone.success) {
        SearchForm();
        ElMessage.success(respone.msg)
      } else {
        ElMessage.error(respone.msg);
      }
    }).catch(() => { })

  }

  // 添加-修改
  function handleUpdate(row) {
    updatePanelVisible.value = true;
    isdisabled.value = false;
    if (row) {
      VisibleTitle.value = "修改"
      isdisabled.value = true;
      nextTick(() => {
        updateFrom.answerA = row.answerA || "";
        updateFrom.answerB = row.answerB || "";
        updateFrom.answerC = row.answerC || "";
        updateFrom.answerD = row.answerD || "";
        updateFrom.answerE = row.answerE || "";
        updateFrom.learningAssessmentId = row.learningAssessmentId;
        updateFrom.menuId = row.menuName;
        updateFrom.moduleId = row.moduleName;
        updateFrom.MenuName = row.menuId;
        updateFrom.moduleName = row.moduleId;
        updateFrom.questionType = row.questionType;
        updateFrom.remark = row.remark;
        updateFrom.title = row.title;
        updateFrom.trueAnswer = row.trueAnswer;
      })
      return
    }
    VisibleTitle.value = "添加";
    updateFrom.learningAssessmentId = null
  }

  // 保存题目
  async function SaveTopic(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      let subData = {};
      if (updateFrom.learningAssessmentId) {
        subData = {
          ...updateFrom,
          ...{
            moduleId: updateFrom.moduleName,
            menuId: updateFrom.MenuName,
            moduleName: updateFrom.moduleId,
            MenuName: updateFrom.menuId
          }
        };
      } else {
        subData = {
          ...updateFrom,
          ...{
            MenuName: updateFrom.menuId.displayName,
            menuId: updateFrom.menuId.id,
            moduleName: updateFrom.moduleId.displayName,
            moduleId: updateFrom.moduleId.id
          }
        }
      }
      // 移除富文本框中的 P 标签
      Object.keys(subData).forEach((key) => {
        if (typeof subData[key] === 'string' && key !== 'questionType') {
          subData[key] = subData[key].replace(/<\/?p>/gi, '');
        }
      });
      const respone = await UpdateLearningAssessment(subData);
      if (respone.success) {
        updatePanelVisible.value = false;
        ElMessage.success(respone.msg);
        row.resetFields()
        SearchForm()
      }
    })
  }

  function handleSizeChange(val: number) {
    SearchForm()
  }

  function handleCurrentChange(val: number) {
    SearchForm()
  }

  function handleSelectionChange(val) {
    SearchForm()
  }

  // 关闭
  function HideVisible(row: FormInstance | undefined) {
    console.log("close", row)
    row.resetFields()
    updatePanelVisible.value = false;
  }


  onMounted(() => {
    getModulName();
    SearchForm()
  })

  return {
    rules,
    columns,
    loading,
    ListFrom,
    dataList,
    ListFroms,
    isdisabled,
    updateFrom,
    SubmitFrom,
    pagination,
    VisibleTitle,
    updatePanelVisible,
    SaveTopic,
    SearchForm,
    HideVisible,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    GetModulChildrens,
    GetModulChildrenss,
    handleCurrentChange,
    handleSelectionChange
  };
}
